<template>
  <div>
    <div class="tableTools">
      <div v-if="selectedRowsData.length" class="select-tools-wrapper">
        选择 {{ selectedRowsData.length }} 项
        <a-button type="text" size="small" @click="clearSelectedRows">取消选择</a-button>
      </div>
      <div v-if="$slots.tableBtns" class="table-btns">
        <slot name="tableBtns" :selected-rows-data="selectedRowsData" />
      </div>
    </div>
    <a-table
      row-key="id"
      class="tableWrap"
      :size="'small'"
      :scroll="scrollConfig"
      :columns="computedColumns"
      :data-source="dataSource"
      :row-selection="showSelection ? rowSelection : void 0"
      :pagination="paginationConfig"
      :loading="loading"
      @change="handleTableChange"
    />
  </div>
</template>

<script setup lang="ts">
import { computed, ref, type PropType } from 'vue';
import type { IColumn, IRow, ITableResponse } from '@/types';
import request from '@/utils/request';
import type { RowSelectionType, TablePaginationConfig, TableRowSelection } from 'ant-design-vue/es/table/interface';

// 获取表格列 配置项,可以不结构仅模板使用的props,如columns，模板编译会自行取值；js中使用，必须结构
const props = defineProps({
  searchState: {
    type: Object as PropType<Record<string, unknown>>,
    default: () => ({}),
  },
  tableListApi: {
    type: String,
    required: true,
  },
  apiMethod: {
    type: String,
    default: 'get',
  },
  columns: {
    type: Array as PropType<IColumn[]>,
    default: () => [],
  },
  scroll: {
    type: Object,
    default() {
      return {
        x: 0,
      };
    },
  },
  // 是否分页
  isPagination: {
    type: Boolean,
    default: true,
  },
  convertFromResponse: {
    type: Function as PropType<(res: ITableResponse) => any>,
    default: (res: ITableResponse) => res,
  },
  // 是否展示表格多选
  showSelection: {
    type: Boolean,
  },
  rowSelectionType: {
    type: String as PropType<RowSelectionType>,
    default: 'checkbox',
  },
  // 默认一页展示多少条数据
  defaultPageSize: {
    type: Number,
    default: 10,
  },
});

const computedColumns = computed<IColumn[]>(() => {
  return props.columns.map(col => {
    if (col.customRender) {
      return col;
    }
    switch (col.type) {
      case 'enum': {
        const values = col.options;
        return {
          ...col,
          customRender({ text }) {
            return values?.length ? values.find(v => v.value === text)?.label : text;
          },
        };
      }
      // case 'datetime':
      //   return {
      //     ...col,
      //     customRender: ({ record }) => utils.dayjsFormat(record[col.dataIndex]),
      //   };
      // case 'date':
      //   return {
      //     ...col,
      //     customRender: ({ record }) => utils.dayjsFormat(record[col.dataIndex], 'YYYY-MM-DD'),
      //   };
      // case 'time':
      //   return {
      //     ...col,
      //     customRender: ({ record }) => utils.dayjsFormat(record[col.dataIndex], 'HH:mm:ss'),
      //   };
      default:
        return col;
    }
  });
});

const pagination = computed(() => {
  const pageSizeOptions = ['10', '20', '50', '100'];
  return {
    total: total.value,
    current: current.value,
    pageSize: pageSize.value,
    showQuickJumper: true,
    showSizeChanger: true,
    pageSizeOptions,
    // showTotal: (total, range) =>
    //   `显示第 ${range[0]} 到第 ${range[1]} 条记录，总共 ${total} 条记录,每页显示 ${pageSize.value} 条记录`,
  };
});
// 分页配置
const paginationConfig = computed(() => {
  if (props.isPagination) {
    return pagination.value;
  }
  return false;
});
// 滚动条配置
const scrollConfig = computed(() => {
  // if (_.isObject(scroll.value)) {
  //   return scroll.value;
  // }
  return { x: 0 };
});

// 多选
const selectedRowsData = ref<IRow[]>([]);
const rowSelection = reactive<TableRowSelection<IRow>>({
  type: props.rowSelectionType, //'checkbox', //'radio',
  selectedRowKeys: [],
  onChange: (selectedRowKeys, selectedRows) => {
    selectedRowsData.value = selectedRows;
    rowSelection.selectedRowKeys = selectedRowKeys;
  },
});

const clearSelectedRows = () => {
  selectedRowsData.value = [];
  rowSelection.selectedRowKeys = [];
};

const total = ref(0);
const current = ref(1);
const pageSize = props.defaultPageSize ? ref(props.defaultPageSize) : ref(10);
const dataSource = ref<IRow[]>([]);
const loading = ref(false);

const getTableData = async () => {
  const { tableListApi, apiMethod } = props;
  if (!tableListApi) {
    console.error('prop of [tableListApi] in props is required!');
    return;
  }

  const res = await request<ITableResponse>({
    url: tableListApi,
    method: apiMethod,
    params: {
      ...props.searchState,
      page: current.value,
      page_size: pageSize.value,
    },
  });

  dataSource.value = res.data.list;
  total.value = res.data.count;
};

getTableData();

// 切换分页
const handleTableChange = (page: TablePaginationConfig) => {
  current.value = page.current || 1;
  pageSize.value = page.pageSize || 10;
  selectedRowsData.value = [];
  getTableData();
};

const refreshTable = () => {
  getTableData();
  clearSelectedRows();
};

defineExpose({
  refreshTable,
  handleTableChange, // 将分页方法暴露给其他组件使用
});
</script>

<style lang="less">
@margin16px: 16px;

.select-tools-wrapper {
  border: 2px solid #1890ff;
  margin-bottom: @margin16px;
  padding: 12px;
  background: hsl(209, 60%, 90%);
}

.table-btns button + button {
  margin-left: @margin16px;
}

.tableWrap {
  margin-top: @margin16px;
}
</style>
